#include "tuya_cloud_types.h"
#include "tal_api.h"
#include "tkl_output.h"
#include "tkl_pwm.h"
#include "led.h"

#define LED_PWM_ID 		TUYA_PWM_NUM_5

TUYA_PWM_BASE_CFG_T led_pwm_cfg;
static uint8_t led_mode, upt_led_mode, last_led_mode;
static uint32_t led_count;


static void led_set_attr(int duty, int freq, TUYA_PWM_POLARITY_E polarity)
{
    OPERATE_RET rt = OPRT_OK;

	led_pwm_cfg.duty = 100 - duty;
	led_pwm_cfg.frequency = freq;
	led_pwm_cfg.polarity = polarity;
	TUYA_CALL_ERR_LOG(tkl_pwm_init(LED_PWM_ID, &led_pwm_cfg));
	TUYA_CALL_ERR_LOG(tkl_pwm_start(LED_PWM_ID));	
}

static void led_set_on(void)
{
	led_set_attr(10000, 10000, TUYA_PWM_POSITIVE);
}

static void led_set_off(void)
{
	led_set_attr(0, 10000, TUYA_PWM_POSITIVE);
}

static void led_flick_fast_l1(void)
{
//	led_set_attr(10, 5, TUYA_PWM_POSITIVE);
	led_count++;
	if(led_count == TIME2TICK(10)) { 
		led_set_on();
	} else if(led_count == TIME2TICK(60)) { // light on 50ms
		led_set_off();
	} else if(led_count == TIME2TICK(3000)) { // light off 3000ms
		led_count = 0;
	} 
}

static void led_flick_fast_l2(void)
{
//	led_set_attr(10, 10, TUYA_PWM_POSITIVE);
	led_count++;
	if(led_count == TIME2TICK(10)) { 
		led_set_on();
	} else if(led_count == TIME2TICK(60)) { // light on 50ms
		led_set_off();
	} else if(led_count == TIME2TICK(3000)) { // light off 3000ms
		led_count = 0;
	} 

}

static void led_flick_slow(void)
{
//	led_set_attr(50, 2, TUYA_PWM_POSITIVE);

	led_count++;
	if(led_count == TIME2TICK(10)) {
		led_set_on();
	} else if(led_count == TIME2TICK(60)) { // light on 50ms
		led_set_off();
	} else if(led_count == TIME2TICK(3000)) { // light off 3000ms
		led_count = 0;
	} 
}

static void led_breathe_slow(void)
{
	led_count += 33; //breathe period 3sec
	if (led_count > 10000) {
		led_count = 0;
	}

	led_set_attr(10000 - led_count, 10000, TUYA_PWM_POSITIVE);
}

static void led_breathe_fast(void)
{
	led_count += 100; //breathe period 1sec
	if (led_count > 10000) {
		led_count = 0;
	}

	led_set_attr(10000 - led_count, 10000, TUYA_PWM_POSITIVE);

}

void led_set_mode(uint8_t mode)
{
	upt_led_mode = mode;
}

void led_loop(void)
{
	//run period is 10sec
	if (led_mode != upt_led_mode) {
		led_mode = upt_led_mode;
		led_count = 0;
	}
	
	switch(led_mode) {
	case LED_TURN_ON:
		if (last_led_mode == led_mode)
			break;
		led_set_on();
		break;
	case LED_TURN_OFF:
		if (last_led_mode == led_mode)
			break;
		led_set_off();
		break;
	case LED_FLICK_SLOW:
		led_flick_slow();
		break;
	case LED_FLICK_FAST:
		led_flick_fast_l1();
		break;
	case LED_BREATHE_SLOW:
		led_breathe_slow();
		break;
	case LED_BREATHE_FAST:
		led_breathe_fast();
		break;
	}
	
out:
	last_led_mode = led_mode;	
}
